﻿#include "widget.h"
#include "ui_widget.h"
#include <QUrlQuery>
#include <QNetworkReply>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //设置热键ctrl+enter发送消息
    ui->textEdit->addAction(ui->actionSend);
    client = new QNetworkAccessManager(this);
    connect(client, &QNetworkAccessManager::finished, this, &Widget::on_reply);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_sendButton_clicked()
{
    QString msg = ui->textEdit->toPlainText();
    ui->textBrowser->append("我：" + msg);
    ui->textEdit->clear();

    QUrlQuery params;
    params.addQueryItem("cmd", "chat");
    params.addQueryItem("appid", "22b4a23787f0f249b1c8f3a04ade8c09");
    params.addQueryItem("userid", "liuyu");
    params.addQueryItem("text", msg);

    QNetworkRequest request(QUrl("http://idc.emotibot.com/api/ApiKey/openapi.php"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    client->post(request, params.toString(QUrl::FullyEncoded).toUtf8());
}


void Widget::on_reply(QNetworkReply* reply)
{
    QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();
    if (json["return"].toInt()) {
        ui->textBrowser->append("错误：" + json["return_message"].toString());
    }
    else {
        foreach (const QJsonValue &i, json["data"].toArray()) {
            if (i["type"] == "text") {
                ui->textBrowser->append("卡卡：" + i["value"].toString());
            }
        }
    }
    reply->deleteLater();
}
